<?php
namespace app\admin\controller;
use think\Db;

class Book extends Common
{
	public function index(){
	  // $data = Db::name('book_info')->where('status',1)->select();
	  $data = model("Book")->getDataAll(1);
	  // dump($data);die;
	  $this->assign('data',$data);

	  return $this->fetch();
	}

	//软删除
    public function del(){
    	//获取的是一个数组
    	$ids = input('post.ids/a');
    	//将数组转为字符串 以逗号分隔
    	$ids = implode(',',$ids);
    	//软删除 更新状态
    	$result = Db::name('book_info')->where("id in ($ids)")->setField('status',0);
    	if($result){
    		$this->success("删除成功");
    	}else{
    		$this->error("删除失败");
    	}
    }

     public function add(){
        if (request()->isPost()) {
             $data = input('post.data/a');
             // dump($data);die;
             if(!$data){
                return json(array('code'=>0,'msg'=>"参数错误"));
             }
             $data['add_time'] = date('Y-m-d H:i:s');
             $result = model('Book')->addBook($data);

             if($result){
                    return json(['code'=>1,'msg'=>'添加成功']);
             }else{
                    return json(['code'=>0,'msg'=>'添加失败']);
             }


        }else{
            $category = Db::name('category')->where('status',1)->select();
            $this->assign('category',$category);

            return $this->fetch();
        }
    
    }

    public function addChapter($id = ''){
    	if(request()->isPost()){
    			$data = input('post.data/a');
    			$list = ['book_id'=>$data['id'],'chapter_id'=>$data['chapter_id'],'chapter'=>$data['chapter'],'content'=>$data['editorValue'],'add_time'=>date('Y-m-d H:i:s')];

    			// $numold = Db::name('book_info')->where('id',$id)->field('chapter_num')->find();
    			// dump($numold);die;
    			
    			// $num = Db::name('book_info')->where('id',$id)->insert(['chapter_num'=> +1]);

    			$result = Db::name('chapter')->insert($list);
    			if($result){
                    return json(['code'=>1,'msg'=>'添加成功']);
	             }else{
	                    return json(['code'=>0,'msg'=>'添加失败']);
	             }
    			// dump($data);die;
    	}else{
    		$data = Db::name('book_info')->where('id',$id)->find();
			$this->assign('data',$data);
    		$info = Db::name('chapter')->where('book_id',$id)->field('chapter_id')->field('chapter')->order('chapter_id desc')->select();

    		$slice_data = array_slice($info,0,6);
    		// dump($data);die;
    		$this->assign('info',$slice_data);

    		return $this->fetch();
    	}
    	
    }
}